package com.lollipop.websocket.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.lollipop.websocket.service.impl.UserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: J.K
 * @Date: 2021-06-07 15:24
 * @Description:
 */
@Controller
@RequestMapping("qr")
public class QrCodeController {
    @Autowired
    private UserTokenService userTokenService;

    /**
     * 获取登录二维码、放入Token
     */
    @RequestMapping(value = "/getLoginQr", method = RequestMethod.GET)
    public void createCodeImg(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");

        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        try {
            // 这里没啥操作，就是生成一个UUID插入user_token表里
            String uuid = userTokenService.createQrImg();
            response.setHeader("uuid", uuid);
            // 生成二维码到输出流,这里是开源工具类 hutool里的QrCodeUtil
            QrCodeUtil.generate(uuid, 300, 300, "jpg", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 确认身份接口：确定身份以及判断是否二维码过期等
     *
     * @param token
     * @param userId
     * @return
     */
    @RequestMapping(value = "/bindUserIdAndToken", method = RequestMethod.GET)
    @ResponseBody
    public void bindUserIdAndToken(@RequestParam("token") String token, @RequestParam("userId") Integer userId,
                                   @RequestParam(required = false, value = "projId") Integer projId) {

        try {
            userTokenService.bindUserIdAndToken(userId, token, projId);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
